<script lang="ts" setup>
import type { FormInstance } from "element-plus"
import type { LoginRequestData } from "./apis/type"
import { useSettingsStore } from "@/pinia/stores/settings"
import { useUserStore } from "@/pinia/stores/user"
import { Key, Loading, Lock, Picture, User } from "@element-plus/icons-vue"
import {  loginApi } from "./apis"
import { useFocus } from "./composables/useFocus"
import { login } from "@@/utils/im"
// dataRes

import { dataRes } from './apis/type';
import {useI18n} from 'vue-i18n'
const {locale,t} = useI18n()



const router = useRouter()

const userStore = useUserStore()

const settingsStore = useSettingsStore()

const { isFocus, handleBlur, handleFocus } = useFocus()

/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)

/** 登录按钮 Loading */
const loading = ref(false)

/** 验证码图片 URL */
const codeUrl = ref("")

// 翻译列表
const optionsTraslates = ref([
  {
    value: 'zh',
    label: '中文(CN)',
  },
  {
    value: 'ru',
    label: '俄文(RU)',
  },
]);


/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: "",
  password: "",
  aid: 1,
  locale: settingsStore.locale,
})

/** 登录表单校验规则 */
const loginFormRules = {
  username: [
    { required: true, message: t("login.请输入用户名"), trigger: "blur" }
  ],
  password: [
    { required: true, message: t("login.请输入密码"), trigger: "blur" },
  ],
}

function setLocal(data: dataRes) {
  // 登录时候设置语言
  let loc = data.country == 0 ? 'zh' : 'ru';
  localStorage.setItem('country', loc);
  settingsStore.locale = loc;
  // locale.value = loc;
  localStorage.setItem('lang', settingsStore.locale);
  userStore.setBid(data.bid);
  let isFirst = !data.address? "true" : "false";
  userStore.setFirstLogin(isFirst);
}
async function language() {
  // localStorage.setItem('country', e);
  // localStorage.setItem('lang', e);
  loginFormRef.value?.resetFields() // 先重置表单值
  nextTick(() => {
    loginFormRef.value?.clearValidate() // 再清除校验状态
  })
  window.navigation.reload();

}

/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid: any) => {
    if (!valid) {
       ElMessage.error(t('common.请输入用户名或密码'))
      return
    }
    loading.value = true
    loginApi(loginFormData).then(({ data }) => {
      setLocal(data);
      // return false;
      setTimeout(() => {
        userStore.setToken(data.token)
        if(!data.address) {
          router.push("/shop/ShopInfo")
        }else {
          router.push("/")
        }
      }, 70);

    }).catch(() => {
      loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}
watch(()=> settingsStore.locale,(val:string)=> {
  locale.value = val;
  let arr: { value: string; label: string }[] = [];
  if (val == 'ru') {
    arr = [
      {
        value: 'zh',
        label: 'CN',
      },
      {
        value: 'ru',
        label: 'RU',
      },
    ];
  } else {
    arr = [{
      value: 'zh',
      label: '中文(CN)',
    },
    {
      value: 'ru',
      label: '俄文(RU)',
    }]
  }
  optionsTraslates.value = arr;

})



</script>

<template>
  <div class="login-container flex flex-justify-end flex-items-center">
    <div class="login-card">
      <div class="translate-cn">
        <el-select
          v-model="settingsStore.locale"
          placeholder="请选择语言"
          w-138px
          h-32px
          class="translate-select"
          @change="language"
        >
          <el-option
            v-for="item in optionsTraslates"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="content">
        <div class="flex flex-col flex-items-center flex-justify-center mb-50px">
          <div class="font-500 font-size-40px color-#1D2129">{{ $t("login.欢迎登录") }}</div>
          <div class="w-55px h-6px bg-#007AFF mt-6px border-rd-16px"></div>
          <div class="font-500 font-size-30px color-#1D2129 mt-24px w-320px">{{ $t('login.GLUZ商家后台管理系统') }}</div>
        </div>
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input
              v-model.trim="loginFormData.username"
              :placeholder="$t('login.请输入用户名')"
              type="text"
              tabindex="1"
              :prefix-icon="User"
              size="large"
              class="h-60px font-size-16px"
            />
          </el-form-item>
          <el-form-item prop="password" mb-0>
            <el-input
              v-model.trim="loginFormData.password"
              :placeholder="$t('login.请输入密码')"
              type="password"
              tabindex="2"
              :prefix-icon="Lock"
              size="large"
              show-password
              @blur="handleBlur"
              @focus="handleFocus"
              class="h-60px font-size-16px"
            />
          </el-form-item>

          <el-button class="h-60px mt-50px font-size-16px" :loading="loading" type="primary" size="large" @click.prevent="handleLogin">
            {{ $t('login.登录') }}
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  background: #e3f0ff url('/static/img/login-bg.png') no-repeat ;
  background-size:  90% auto;
  background-position: left;
  box-sizing: border-box;
  padding: 20px;
  .login-card {
    width: 639px;
    height: 100%;
    flex-shrink: 0;
    border-radius: 24px;
    background: rgba(255, 255, 255, 0.90);
    backdrop-filter: blur(2px);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .translate-cn {
      position: absolute;
      top: 20px;
      right: 20px;
      .translate-select {
        :deep(.el-select__wrapper ){
          border-radius: 16px;
          background: #F2F3F5;
        }
      }

    }
    .content {
      padding: 0 56px;
      width: 100%;
      .el-form {
        width: 100%;
        :deep(.el-input-group__append) {
          padding: 0;
          overflow: hidden;
          .el-image {
            width: 100px;
            height: 40px;
            border-left: 0px;
            user-select: none;
            cursor: pointer;
            text-align: center;
          }

        }
        .el-input {
          :deep(.el-input__inner) {
            height: 50px;
          }

        }
      }

      .el-button {
        width: 100%;
      }
    }
  }
}




</style>
